<template>
    <div>
        <div class="from">
            <el-form :inline="true" :model="searchMap" class="demo-form-inline" ref="searchFormRef">
                <el-form-item label="教师查询" prop="teacher_id">
                    <el-select v-model="searchMap.teacher_id" placeholder="请选择教师" clearable>
                        <el-option v-for="teacher in teachers" :key="teacher._id" :label="teacher.name"
                            :value="teacher._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学管查询" prop="manager_id">
                    <el-select v-model="searchMap.manager_id" placeholder="请选择学管" clearable>
                        <el-option v-for="manager in managers" :key="manager._id" :label="manager.name"
                            :value="manager._id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onQuery">查询</el-button>
                    <el-button  @click="resetFrom(searchFormRef)">重置</el-button>
                    <el-button type="primary" @click="addClass">添加</el-button>
                </el-form-item>
            </el-form>
        </div>
        <el-table :data="classes" style="width: 100%;height: 380px;" border>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column label="班级名称" prop="classname"></el-table-column>
            <el-table-column label="授课教师" prop="teacher_id" :formatter="formatterTeacher"></el-table-column>
            <el-table-column label="学管" prop="manager_id" :formatter="formatterManager"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row._id)">
                        编辑
                    </el-button>
                    <el-button type="danger" @click="handleDelete(scope.row._id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

         <!-- 新增或更新班级 -->
        <el-dialog v-model="classFromVisible" :title="title" width="500">
            <el-form :model="classFrom" ref="classFormRef" :rules="rules">
                <el-form-item label="班级名称" prop="classname">
                    <el-input v-model="classFrom.classname"/>
                </el-form-item>
                <el-form-item label="授课教师" prop="teacher_id">
                    <el-select v-model="classFrom.teacher_id" placeholder="请选择教师" clearable>
                        <el-option v-for="teacher in teachers" :key="teacher._id" :label="teacher.name"
                            :value="teacher._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="学管" prop="manager_id">
                    <el-select v-model="classFrom.manager_id" placeholder="请选择学管" clearable>
                        <el-option v-for="manager in managers" :key="manager._id" :label="manager.name"
                            :value="manager._id" />
                    </el-select>
                </el-form-item>
                
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(classFormRef)">
                        确定
                    </el-button>
                    <el-button @click="classFromVisible = false">取消</el-button>
                    
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { cla, pageClass, searchMapData } from '@/api/class/type';
import { nextTick, onMounted, reactive, ref } from 'vue';
import useRoleStore from '@/store/modules/role';
import useUserStore from '@/store/modules/user';
import useClassStore from '@/store/modules/class';
import type { userInfoData } from '@/api/user/type';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
const roleStore = useRoleStore();
const userStore = useUserStore();
const classStore = useClassStore();
const searchMap = ref<searchMapData>({
    teacher_id: undefined,
    manager_id: undefined
});

//提取出角色中的教师和学管的id
//定义教师和学管的存储数组
const teacherId = ref<string>();
const managerId = ref<string>();

//获取角色列表中的教师和学管的id
const getTM = () => {
    roleStore.roleList().then(() => {
        roleStore.roles?.forEach((item) => {
            if (item.name === "教师") {
                teacherId.value = item._id
            } else if (item.name == "学管") {
                managerId.value = item._id
            }
        })
    })


}
//获取所有用户,用户选择时候回显
const users = ref([])
//获取角色为教师的用户
const teachers = ref<userInfoData[]>([]);
//获取角色为学管的用户
const managers = ref<userInfoData[]>([]);
//获取用户中的教师和学管
const getTeacherManager = () => {

    userStore.getUserAll().then(() => {
        //@ts-ignore
        users.value = userStore.users;
        users.value.forEach((item: userInfoData) => {
            if (item.role_id == teacherId.value) {
                teachers.value?.push(item);
            } else if (item.role_id == managerId.value) {
                managers.value?.push(item);
            }
        })

    })
}
//获取条件查询form表单
const searchFormRef = ref()
//重置条件查询表单
const resetFrom = (formEl:FormInstance|undefined)=>{
    if(!formEl) return;
    formEl.resetFields();
}


//条件分页查询
//当前页码:
const currentPage = ref(1);
//每页展示多少
const pageSize = ref(5);
//分页返回的总条数
const total = ref(0);
//显示条数大小改变的时候触发的方法
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    //分页一次
    onQuery()
    console.log(`当前一页总条数:${val}`);
}
//改变当前页面
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    //分页一次
    onQuery()
    console.log(`当前页码:${val}`);
}
const classes = ref<cla[]>()
const onQuery = () => {
    classStore.pageClass({page:currentPage.value,size:pageSize.value,searchMap:searchMap.value}).then((res)=>{
        console.log("res:",res);
        classes.value = res?.data as cla[];
        total.value = res?.total as number;
    })
}
/* 班级列表 */


//格式化教师名称
const formatterTeacher = (row: any, column: any, cellValue: string, index: number)=>{
    let teacher = teachers.value.find(item=>item._id == cellValue) as userInfoData || {}
    return teacher.name;
}
const formatterManager = (row: any, column: any, cellValue: string, index: number)=>{
    let manager = managers.value.find(item=>item._id == cellValue) as userInfoData || {}
    return manager.name;
}
/* 添加班级 */
//对话框标题
const title = ref();
const classFromVisible = ref(false);
const classFormRef = ref();
const classFrom = ref<cla>({
    classname:"",
    teacher_id:"",
    manager_id:""    
});
//新增班级按钮触发的方法
const addClass = ()=>{
    classFromVisible.value = true;
    title.value = "新增班级"
    nextTick(()=>{
        classFormRef.value.resetFields();
    })
};


/* 编辑班级 */
const handleEdit = (_id:string)=>{
    classFromVisible.value = true;
    title.value = "编辑班级";
    console.log(_id);
    
    classStore.findById(_id).then((res)=>{
        
        classFrom.value = {...res};
    })
}
const checkClassName = (rule: any, value: any, callback: any) => {
    value = value.trim();
  if (value == "") {
    return callback(new Error('请输入班级名称'))
  }else{
    return callback();
  }
};
const rules = reactive<FormRules>({
  classname: [{ required:true,validator:checkClassName, trigger: 'blur' }],
  teacher_id:[{ required:true, trigger: 'blur'}],
  manager_id:[{required:true, trigger: 'blur'}]
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
        if(title.value == "新增班级"){
            //验证都成功后,发送添加请求
        classStore.addClass(classFrom.value).then(()=>{
            //刷新页面
            onQuery()
            //关掉对话框
            classFromVisible.value = false
            ElMessage({
                type:'success',
                message:"添加成功"
            })
        }).catch((err)=>{
            classFromVisible.value = false
            ElMessage({
                type:"error",
                message:err.msg
            })
        })
        }else if(title.value == "编辑班级"){
            //编辑学校的校验
            classStore.updateClass(classFrom.value).then(()=>{
                //刷新页面
                onQuery()
                //关掉对话框
                classFromVisible.value = false
                ElMessage({
                type:'success',
                message:"修改成功"
                })
            }).catch((err)=>{
                classFromVisible.value = false
                ElMessage({
                    type:"error",
                    message:err.msg
                })
            })
            
        }
    } else {
      console.log('error submit!')
    }
  })
}

/* 删除专业 */
const handleDelete = (_id: string) => {
    classStore.deleteClass(_id).then(() => {
        //删除成功
        onQuery()
        ElMessage({
            type: "success",
            message: "删除成功"
        })
    }).catch((err)=>{
        ElMessage({
            type: "error",
            message: err.msg
        })
    })

}
onMounted(() => {
    getTM()
    getTeacherManager()
    onQuery()
})
</script>

<style scoped>
.demo-form-inline .el-input {
    --el-input-width: 150px;
}

.demo-form-inline .el-select {
    --el-select-width: 150px;
}

.from {
    margin: 20px;
}
.el-pagination {
    display: flex;
    justify-content: center;
}
</style>